<template>
  <div>
    <div class="query-form">
      <el-form
        :inline="true"
        size="small"
        :model="role"
        ref="role"
        class="demo-form-inline"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="role.roleName"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchRole">查询</el-button>
          <el-button @click="resetForm('role')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button size="small" type="primary" @click="handleOpen"
          >创建</el-button
        >
      </div>
      <el-table size="mini" :data="roleList" style="width: 100%">
        <el-table-column
          v-for="(item, index) in tableDate"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :formatter="item.formatter"
        >
        </el-table-column>
        <el-table-column label="操作" width="250px">
          <template slot-scope="scope">
            <el-button size="mini" @click="editRole(scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="primary"
              @click="permissionsOpen(scope.row)"
              >权限设置</el-button
            >
            <el-button size="mini" type="danger" @click="delRole(scope.row._id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        @current-change="changePage"
        background
        layout="prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 角色表单 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form
        :model="roleForm"
        :rules="rules"
        ref="roleForm"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="roleForm.remark"
            type="textarea"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="operationRole">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 权限表单 -->
    <el-dialog title="权限设置" :visible.sync="dialogVisible" width="50%">
      <el-form
        :model="permissionForm"
        :rules="rules"
        ref="roleForm"
        label-width="100px"
      >
        <el-form-item label="角色名称">
          <span>:&emsp;{{ permissionRoleName }}</span>
        </el-form-item>
        <el-form-item label="选择权限">
          <el-tree
            v-model="permissionForm.permissionList"
            ref="tree"
            :data="menuList"
            show-checkbox
            default-expand-all
            node-key="_id"
            :props="{ label: 'menuName' }"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handlePermission">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
export default {
  data() {
    return {
      dialogFormVisible: false,
      dialogVisible: false,
      permissionForm: {
        permissionList: {
          halfCheckedKeys: [],
          checkedKeys: [],
        },
      },
      menuList: [],
      permissionRoleName: "",
      permissionRoleId: "",
      title: "",
      role: {
        roleName: "",
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      roleList: [],
      roleForm: {
        action: "",
        roleName: "",
        remark: "",
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
      tableDate: [
        {
          prop: "roleName",
          label: "角色名称",
          width: "",
        },
        {
          prop: "remark",
          label: "备注",
          width: "",
        },
        {
          prop: "permissionList",
          label: "权限列表",
          width: "",
        },
        {
          prop: "updateTime",
          label: "更新时间",
          width: "",
          formatter(row, column, value) {
            return moment
              .parseZone(value)
              .local()
              .format("YYYY-MM-DD HH:mm:ss");
          },
        },
        {
          prop: "createTime",
          label: "创建时间",
          width: "",
          formatter(row, column, value) {
            return moment
              .parseZone(value)
              .local()
              .format("YYYY-MM-DD HH:mm:ss");
          },
        },
      ],
    };
  },
  mounted() {
    this.getRoleList();
    this.getMenuList();
  },
  methods: {
    async getRoleList() {
      let res = await this.roleApi.getRoleList(this.role);
      this.roleList = res.list;
      this.total = res.page.total;
    },
    searchRole() {
      this.getRoleList();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.getRoleList();
    },
    changePage(page) {
      this.role.pageNum = page;
      this.getRoleList();
    },
    handleOpen() {
      this.dialogFormVisible = true;
      this.roleForm.action = "create";
      this.title = "角色新增";
    },
    operationRole() {
      this.$refs["roleForm"].validate(async (valid) => {
        if (valid) {
          let res = await this.roleApi.operationRole(this.roleForm);
          this.$refs["roleForm"].resetFields();
          this.dialogFormVisible = false;
          this.getRoleList();
          this.$message.success({
            message: "创建成功",
            offset: 100,
          });
        } else {
          this.$message.error({
            message: "输入内容有误, 请重新输入",
            offset: 100,
          });
          return false;
        }
      });
    },
    editRole(row) {
      this.dialogFormVisible = true;
      this.roleForm.action = "edit";
      this.title = "角色编辑";
      this.$nextTick(() => {
        Object.assign(this.roleForm, row);
      });
    },
    async delRole(id) {
      let res = await this.roleApi.operationRole({ action: "delete", _id: id });
      console.log(res);
      this.getRoleList();
      this.$message.success({
        message: "删除成功",
        offset: 100,
      });
    },
    permissionsOpen(row) {
      this.dialogVisible = true;
      // console.log(row);
      this.permissionRoleName = row.roleName;
      this.permissionRoleId = row._id;
      let { checkedKeys } = row.permissionList;
      // console.log(checkedKeys);
      this.$nextTick(() => {
        this.$refs["tree"].setCheckedKeys(checkedKeys);
      });
    },
    async getMenuList() {
      let res = await this.userApi.getMenuList();
      this.menuList = res.menuList;
      // console.log(this.menuList);
    },
    // 提交权限数据
    async handlePermission() {
      // 获取到选中的节点
      let nodes = this.$refs["tree"].getCheckedNodes();
      // 获取半选中的父节点
      let halfKeys = this.$refs["tree"].getHalfCheckedKeys();
      // 创建两个变量  保存选中的子节点和半选中的父节点
      let childrenKeys = [];
      let parendKeys = [];

      nodes.map((item) => {
        console.log(item);
        if (item.children) {
          parendKeys.push(item._id);
        } else {
          childrenKeys.push(item._id);
        }
      });

      let params = {
        _id: this.permissionRoleId,
        permissionList: {
          halfCheckedKeys: parendKeys.concat(halfKeys),
          checkedKeys: childrenKeys,
        },
      };

      let res = await this.roleApi.settingPermission(params);
      // console.log(res);
      this.dialogVisible = false;
      this.getRoleList();
      this.$message.success({
        message: "权限设置成功",
        offset: 100,
      });
    },
  },
};
</script>

<style scoped >
</style>
